package net;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;




public class ChatClient {
    private static Socket socket;


    public  ChatClient(){
        try {
            socket = new Socket("127.0.0.1",8080);
        }catch (IOException e){
            System.out.println("连接失败");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void start(){
        Scanner sc=null;
        PrintWriter pw=null;
        BufferedReader br=null;
        try {
            pw = new PrintWriter(socket.getOutputStream(),true);

            new Thread(new ServerHandler()).start();

            sc=new Scanner(System.in);
                    System.out.print("发送消息内容:");
                    while (true) {
                        String chat = sc.nextLine();
                        if ("exit".equalsIgnoreCase(chat)) {
                            System.out.println("聊天结束，关闭聊天室!");
                            break;
                        }
                        pw.println(chat);
                    }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            sc.close();
            if (pw!=null)pw.close();

            if (socket != null)try {
                socket.close();
                System.out.println("客户端退出");
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }

    private class ServerHandler implements Runnable{

        @Override
        public void run() {
            BufferedReader br = null;
            String str;

            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
                while (true) {
                    if ((str = br.readLine()) != null) {
                        System.out.println(str);
                    }
                }
                } catch(IOException e){
                    e.printStackTrace();
                }

        }
    }


    public static void main(String[] args) {
        new ChatClient().start();
    }
}
